import { reactive, ref, toRefs } from 'vue';
import { usePullDownRefresh, useReachBottom, stopPullDownRefresh } from '@tarojs/taro';

/**
 * @param { PagerOptions } options
 * @returns
 */
export const usePager = options => {
  const { handler, immediate = true, limit = 10, delay = 500, onPullDownRefresh, onError, transform, onOver } = options;
  const pager = reactive({
    loading: false,
    finish: false,
    isEmpty: true
  });
  const list = ref([]);

  const next = force => {
    if (!force && (pager.loading || pager.finish)) return Promise.resolve([]);
    pager.loading = true;
    return handler(list.value.length, limit)
      .then(data => transform?.call(null, data) ?? data)
      .sleep(delay)
      .then(data => {
        if (data.length < limit) {
          pager.finish = true;
          onOver?.call(null);
        }
        list.value.push(...data);
        if (list.value.length == 0) {
          pager.isEmpty = true;
        } else {
          pager.isEmpty = false;
        }
      })
      .finally(() => (pager.loading = false))
      .catch(err => {
        onError?.call(null, err);
        return Promise.reject(err);
      });
  };
  const reset = () => {
    pager.finish = false;
    list.value = [];
  };
  const reload = async () => {
    reset();
    await next();
  };
  // 立即执行
  if (immediate) {
    next();
  }
  usePullDownRefresh(async () => {
    onPullDownRefresh?.call(null, stopPullDownRefresh);
    reset();
    next().finally(stopPullDownRefresh);
  });
  useReachBottom(async () => {
    await next();
  });
  return {
    reset,
    next,
    reload,
    pager,
    list,
    ...toRefs(pager)
  };
};
